<section>
	<div class="page-header">
		<h2><?php echo $title; ?></h2>
	</div>
	
	<?php echo form_open('', array('autocomplete' => 'off')); ?>
		<div class="clearfix">
			<label>Name</label>
			<div class="input">
				<input type="text" name="role_name" />
			</div>
		</div>
		<div class="clearfix">
			<label>Permissions</label>
			<div class="input">
				<ul class="inputs-list parent">
					<?php
					foreach ($permissions as $perm)
					{
						if ($perm['parent_permission'] != 0) continue;
						
						echo '<li><label><input type="checkbox" name="permission[]" value="' . $perm['permission_id'] . '" /><span>' . $perm['permission_name'] . '</span></label>';
						
						$ul = '<ul class="inputs-list">';
						$x  = 0;
						
						foreach ($permissions as $perms)
						{
							if ($perms['parent_permission'] == $perm['permission_id'])
							{
								$x++;
								if ($x == 1) echo $ul;
								
								echo '<li><label><input type="checkbox" name="permission[]" value="' . $perms['permission_id'] . '" /><span>' . $perms['permission_name'] . '</span></label></li>';
							}
						}
						
						if ($x != 0)
						{
							echo '</ul></li>';
							$x = 0;
						}
					}
						
					?>
				</ul>
			</div>
		</div>
		<div class="clearfix">
			<label>Menus</label>
			<div class="input" style="overflow: auto;">
				<ul class="inputs-list parent menu-sortable">
					<?php
					foreach ($menus as $menu)
					{
						if ($menu['parent_menu'] != 0) continue;
						
						echo '<li><label><input type="checkbox" name="menus[]" value="' . $menu['menu_id'] . '" /><span>' . $menu['name'] . '</span></label>';
						
						$ul = '<ul class="inputs-list menu-sortable">';
						$x  = 0;
						
						foreach ($menus as $menu2)
						{
							if ($menu2['parent_menu'] == $menu['menu_id'])
							{
								$x++;
								if ($x == 1) echo $ul;
								
								$spn = $menu2['divider'] == 'y' ? '** DIVIDER **' : $menu2['name'];
								
								echo '<li><label><input type="checkbox" name="menus[]" value="' . $menu2['menu_id'] . '" /><span>' . $spn . '</span></label></li>';
							}
						}
						
						if ($x != 0)
						{
							echo '</ul></li>';
							$x = 0;
						}
					}
					?>
				</ul>
			</div>
		</div>
		<div class="actions">
			<button type="submit" class="btn primary">Save</button>
			<?php echo anchor('users/roles', 'Cancel', array('class' => 'btn')); ?>
		</div>
	</form>
</section>

<script>
	$('.inputs-list.menu-sortable').sortable();
	$('.inputs-list.menu-sortable').disableSelection();
	
	$('.inputs-list.parent > li > label > input').change(function() {
		$(this).parents('li').children('ul').find(':checkbox').prop('checked', this.checked);
	});
	
	$('.inputs-list:not(.parent) > li > label > input').click(function() {
		$(this).parents('.inputs-list:not(.parent)').prev().find(':checkbox:eq(0)').prop('checked', true);
	});
</script>